#!/bin/bash
#需要传入变量ROLE(本机身份,用于判断),MASTER(从节点需要传入用于指定主节点)

#错误判断
function test_order() {
  if [ $? -ne 0 ]; then
    echo "命令执行错误" 
    exit 1
  fi
}


#主节点配置
function master() {
  #创建用户(在没有传入MYSQL_USER和MYSQL_PASSWORD时启用)
  #CREATE_SQL="create user "${MYSQL_USER}"@'%' identified by '${MYSQL_PASSWORD}';"
  #授权复制用户
  GRANT_SQL="grant replication slave on *.*  to "${MYSQL_USER}"@'%';"
  #刷新权限
  FLUSH_SQL="flush privileges;"
  mysql -u 'root' -p"${MYSQL_ROOT_PASSWORD}" -e "${GRANT_SQL}" &>/dev/null
  test_order
  mysql -u 'root' -p"${MYSQL_ROOT_PASSWORD}" -e "${FLUSH_SQL}" &>/dev/null
  test_order
}


#从节点配置
function slave() {
  SHOW_STATUS_SQL1="SHOW MASTER STATUS;"
  FILE="$(mysql -u'root' -p"${MYSQL_ROOT_PASSWORD}" -h ${MASTER} -e"${SHOW_STATUS_SQL1}"|grep mysql|awk '{print $1}')" 
  POSITION="$(mysql -u'root' -p"${MYSQL_ROOT_PASSWORD}" -h ${MASTER} -e"${SHOW_STATUS_SQL1}"|grep mysql|awk '{print $2}')" 
  #从节点开启复制
  CHANGE_MASTER_SQL="change master to master_host='${MASTER}',master_user='${MYSQL_USER}',master_password='${MYSQL_PASSWORD}',master_log_file='${FILE}',master_log_pos=${POSITION};"
  START_SLAVE="start slave;"
  #指定主节点
  mysql -u 'root' -p"${MYSQL_ROOT_PASSWORD}" -e "${CHANGE_MASTER_SQL} ${START_SLAVE}" 
  test_order
}

function check() {
  for  i   in  {1..5}
  do
    echo 1
    mysqladmin -u root -p"${MYSQL_ROOT_PASSWORD}" -h ${MASTER} ping
  done
}


#实现主函数
function main() {
  #角色为master
  if [ "${ROLE}" = "master" ]; then 
    echo "1"
    master
  #角色为slave
  elif [ "${ROLE}" = "slave" ]; then
    echo "2"
    slave
  elif [ "${ROLE}" = "m_s" ]; then
    echo "3"
    master
    check
    slave
  else
    echo "没有指定角色或角色错误" 
  fi
}


main



